package com.ajaxlord.confluence.plugin.json.actions;

import com.atlassian.confluence.security.Permission;
import com.atlassian.confluence.setup.settings.Settings;
import com.atlassian.confluence.util.GeneralUtil;
import com.opensymphony.util.TextUtils;
import com.opensymphony.webwork.ServletActionContext;
import org.randombits.confluence.support.PluginActionSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.ListIterator;

public abstract class JSONActionSupport extends PluginActionSupport {
    public static final String JSON_CONTENT_TYPE = "text/json";

    //TODO 最后改成text/json

    private GeneralUtil generalUtil = new GeneralUtil();
    private String referer;
    private Settings settings;

    public String execute() throws Exception {
        String status = doExecute();
        applyContentType();
        return status;
    }

    protected List removeInvisibleContent(List content) {
        if (content != null) {
            ListIterator i = content.listIterator();
            while (i.hasNext()) {
                Object object = i.next();
                if (!permissionManager.hasPermission(getRemoteUser(), Permission.VIEW, object))
                    i.remove();
            }
        }

        return content;
    }

    protected String doExecute() throws Exception {
        return SUCCESS;
    }

    protected static void applyContentType() {
        getResponse().setContentType(getContentType());
    }

    public static String getContentType() {
        return JSON_CONTENT_TYPE;
    }

    public static HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    public GeneralUtil getGeneralUtil() {
        return generalUtil;
    }

    public String getRefererURL() {
        if (referer == null) {
            HttpServletRequest request = getRequest();
            referer = request.getHeader("Referer");

            if (!TextUtils.stringSet(referer))
                return null;

            if (referer.indexOf("logout") > -1 || referer.indexOf("login") > -1)
                return null;

            String baseUrl = getSettings().getBaseUrl();

            if (referer.indexOf("://") != -1 && referer.startsWith(baseUrl)) {
                referer = referer.substring(baseUrl.length());
                if (!referer.startsWith("/"))
                    referer = "/" + referer;
            }
        }

        return referer;
    }

    private Settings getSettings() {
        return settings;
    }

    public void setSettings(Settings settings) {
        this.settings = settings;
    }
}
